package cn.enilu.flash.api.controller.h5;

import cn.enilu.flash.bean.entity.order.WithdrawOrder;
import cn.enilu.flash.bean.entity.system.User;
import cn.enilu.flash.bean.entity.task.MoneyInfo;
import cn.enilu.flash.bean.vo.front.Ret;
import cn.enilu.flash.bean.vo.front.Rets;
import cn.enilu.flash.security.JwtUtil;
import cn.enilu.flash.service.order.WithdrawOrderService;
import cn.enilu.flash.service.system.UserService;
import cn.enilu.flash.service.task.MoneyInfoService;
import cn.enilu.flash.utils.StringUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;

@RestController
@RequestMapping("/h5")
public class H5WithdrawController {
    @Autowired
    private WithdrawOrderService withdrawService;
    @Autowired
    private MoneyInfoService moneyInfoService;
    @Autowired
    private UserService userService;

    /**
     * 默认支付宝，仅开放支付宝
     * @param realName 真实姓名
     * @param account 提现账户
     * @param money 提现金额
     * @param type 提现类型 1、支付宝 2、微信 默认支付宝
     * @return
     */
    @PostMapping("/withdraw")
    @Transactional
    public Ret withdraw(String realName, String account, BigDecimal money,@RequestParam(defaultValue = "1") Integer type) {
        if(StringUtil.isNullOrEmpty(realName) || StringUtil.isNullOrEmpty(account)){
            return Rets.failure("请完善提现信息！");
        }
        User user = userService.get(JwtUtil.getUserId());
        if(user==null){
            return Rets.failure("用户信息异常");
        }
        if(user.getBalance().compareTo(money)<0){
            return Rets.failure("提现金额不能大于用户余额！");
        }
        WithdrawOrder withdrawOrder = new WithdrawOrder();
        withdrawOrder.setCreateTime(new Date());
        withdrawOrder.setCreateBy(user.getId());
        withdrawOrder.setType(type);
        withdrawOrder.setMoney(money);
        withdrawOrder.setRealName(realName);
        withdrawOrder.setAccount(account);
        withdrawOrder = withdrawService.insert(withdrawOrder);

        /*
         * 调用支付宝转账APi
         */
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");  //gateway:支付宝网关（固定）https://openapi.alipay.com/gateway.do
        certAlipayRequest.setAppId("20190619xxxxxxxxxx");  //APPID 即创建应用后生成,详情见创建应用并获取 APPID
        certAlipayRequest.setPrivateKey("app_privateKeyhbskaf………………………………");  //开发者应用私钥，由开发者自己生成
        certAlipayRequest.setFormat("json");  //参数返回格式，只支持 json 格式
        certAlipayRequest.setCharset("UTF-8");  //请求和签名使用的字符编码格式，支持 GBK和 UTF-8
        certAlipayRequest.setSignType("RSA2");  //商户生成签名字符串所使用的签名算法类型，目前支持 RSA2 和 RSA，推荐商家使用 RSA2。
        certAlipayRequest.setCertPath("D://app_cert_path/app_cert_path文件"); //应用公钥证书路径（app_cert_path 文件绝对路径）
        certAlipayRequest.setAlipayPublicCertPath("D://alipay_cert_path/alipay_cert_pat文件"); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
        certAlipayRequest.setRootCertPath("D://alipay_root_cert_path/alipay_root_cert_path文件");  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e) {
            return Rets.failure("提现失败~");
        }
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        request.setBizContent("{" +
                "\"out_biz_no\":\""+withdrawOrder.getId()+"\"," +             /*本地订单号*/
                "\"trans_amount\":"+money+"," +                               /*转账金额*/
                "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," +                /*固定值*/
                "\"biz_scene\":\"DIRECT_TRANSFER\"," +                        /*固定值*/
                "\"order_title\":\"用户提现-"+realName+"\"," +                 /*订单标题*/
                "\"payee_info\":{" +
                "\"identity_type\":\"ALIPAY_LOGON_ID\"," +                     /*账户类型：支付宝登录号，支持邮箱和手机号格式*/
                "\"identity\":\""+account+"\"," +                              /*用户账号*/
                "\"name\":\""+realName+"\"," +                                 /**/
                "}," +
                "\"remark\":\"用户提现\"," +
                "\"business_params\":\"{\\\"payer_show_name_use_alias\\\":\\\"true\\\"}\"" +
                "}");
        AlipayFundTransUniTransferResponse response = null;
        try {
            response = alipayClient.certificateExecute(request);
        } catch (AlipayApiException e) {
            return Rets.failure("提现失败~");
        }
        MoneyInfo moneyInfo = null;
        if (response.isSuccess()) { // 调用成功
            moneyInfo = moneyInfoService.setMoneyInfo(null, user.getId(), 2, money); // 减金额，插入资金明细
        } else {
            System.out.println("调用失败");
            throw new RuntimeException("支付宝转账失败!");// 抛出异常，事务回滚
        }
        return moneyInfo == null? Rets.failure("提现失败~"):Rets.success();
    }

}
